package com.jsyxdl.k3cloud.listener.handling;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.dto.PartUsageLink;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.jsyxdl.entity.PartUsageLinkDiffResultDTO;
import com.jsyxdl.entity.PurchaseDiffDTO;
import com.jsyxdl.k3cloud.utils.HttpMethodEnum;
import com.jsyxdl.k3cloud.listener.K3CloudHttpService;
import com.jsyxdl.k3cloud.service.ErpWorkedTaskService;
import com.jsyxdl.k3cloud.utils.PlmPartOptionUtils;
import com.jsyxdl.k3cloud.utils.SendErpDataUtils;
import com.jsyxdl.service.ErpK3cloudService;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.exception.message.SystemErrorCodeEnum;

import java.math.BigInteger;
import java.util.*;

/**
 * 出库申请单处理服务
 */
public class OutboundApplicationHandling implements ErpWorkedTaskService {


    public JSONObject productionCall(Map<String, Object> executionType, FlowObject flowObject, UserDO userDO)
            throws Exception {
        PlmPartOptionUtils plmPartOptionUtils = SpringUtil.getBean(PlmPartOptionUtils.class);
        ErpK3cloudService erpK3cloudService = SpringUtil.getBean(ErpK3cloudService.class);
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);

        String k3cloud = (String) executionType.get("k3cloud");
        String code = (String) executionType.get("code");


        //查询ERP用户
        JSONObject userJson = getErpUser(userDO, executionType);
        if (userJson == null) {
            k3CloudHttpService.saveLogs("","","失败", "查询不到ERP用户信息", "", k3cloud, code);
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("查询不到ERP用户信息");
        }

        BigInteger poid = flowObject.getRefObjectOid();
        String poType = flowObject.getRefObjectOtype();
        PartDetailsVO parent = plmPartOptionUtils.getPartDetailsVO(poid, poType);


        List<Map<String, Object>> options = k3CloudHttpService.getOptions(code, k3cloud);

        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI", true);


        PurchaseDiffDTO purchaseDiffDTO = new PurchaseDiffDTO();
        purchaseDiffDTO.setId(UUID.randomUUID().toString());
        purchaseDiffDTO.setObjectNumber(parent.getObjectNumber());
        purchaseDiffDTO.setVersion(parent.getVersion());
        purchaseDiffDTO.setIteration(parent.getIteration());

        Map<String, Object> inMap = k3CloudHttpService.getInTreeMap(code, k3cloud);

        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
        expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

        ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
        childPartsFiltersDTO.setBaseLineOid("");
        childPartsFiltersDTO.setDate("");
        childPartsFiltersDTO.setExpandCondition("latest");
        childPartsFiltersDTO.setLifecycleStateKey("");
        childPartsFiltersDTO.setPurposeOfBom("");
        childPartsFiltersDTO.setSpareBom("");
        childPartsFiltersDTO.setView(parent.getView());
        List<ChildPartsFiltersDTO> list = new ArrayList<>();
        list.add(childPartsFiltersDTO);
        expandBomTreeByFilterDTO.setConditions(list);

        expandBomTreeByFilterDTO.setExpandLevel("N");
        expandBomTreeByFilterDTO.setFatherNumber(parent.getObjectNumber());
        expandBomTreeByFilterDTO.setFatherOid(String.valueOf(parent.getOid()));
        expandBomTreeByFilterDTO.setFatherOtype(parent.getOtype());
        expandBomTreeByFilterDTO.setFilterMode("0");
        expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
        expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
        expandBomTreeByFilterDTO.setIsApplyRoot(false);
        expandBomTreeByFilterDTO.setIsFilterAttr(false);
        expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
        expandBomTreeByFilterDTO.setIsNestedTree(false);
        expandBomTreeByFilterDTO.setIsQueryIBA(true);

        PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                    Boolean.TRUE);

        List<PartUsageLinkDiffResultDTO> differences = k3CloudHttpService.getErpHistoricalVersion().getPartDiffResults(
                flowObject);
        Map<String, PartUsageLinkDiffResultDTO> differenceMap = new HashMap<>();
        for (int a = 0; a < differences.size(); a++) {
            differenceMap.put(differences.get(a).getObjectNumber(), differences.get(a));
        }

        for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
            PartBomTree partBomTree = result.getPartBomTreeList().get(y);
            if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                if (differenceMap.containsKey(partBomTree.getObjectNumber()) == false) {
                    result.getPartBomTreeList().remove(y);
                    y--;
                }
            }
        }

        if (result.getPartBomTreeList().size() < 2) {
            JSONObject resultObj = new JSONObject();
            resultObj.put("IsSuccess", true);
            resultObj.put("msg", "没有能出库的物料");
            JSONObject responseStatus = new JSONObject();
            responseStatus.put("ResponseStatus", resultObj);
            httpResult.put("Result", responseStatus);
            k3CloudHttpService.saveLogs("","","成功", httpResult.toJSONString(), "", k3cloud, code);
            return httpResult;
        }


        Map<String, PartBomTree> cfpartMap = new HashMap<>();
        Map<String, Object> bomKeyValue = new HashMap<>();

        //取ObjectNumber查询对应的ERP库存
        List<String> objectNumbers = new ArrayList<>();
        //整合相同编码的物料
        for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
            PartBomTree partBomTree = result.getPartBomTreeList().get(y);
            if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                if (partBomTree.getIsLeafNode() == true) {
                    BigInteger oid = partBomTree.getOid();
                    String oType = partBomTree.getOtype();
                    PartUsageLink partUsageLink = plmPartOptionUtils.getPartUsageLink(oid, oType);
                    partBomTree.setAmount(partUsageLink.getAmount());

                    if (differenceMap.containsKey(partBomTree.getObjectNumber())) {
                        PartUsageLinkDiffResultDTO partUsageLinkDiffResultDTO = differenceMap.get(
                                partBomTree.getObjectNumber());
                        partBomTree.setAmount(partUsageLinkDiffResultDTO.getAmountDiff());
                    }

                    //累计相同物料编码的数量
                    if (cfpartMap.containsKey(partBomTree.getObjectNumber())) {
                        PartBomTree pbt = cfpartMap.get(partBomTree.getObjectNumber());
                        pbt.setAmount(pbt.getAmount() + partBomTree.getAmount());
                        result.getPartBomTreeList().remove(y);
                        y--;
                    } else {
                        objectNumbers.add(partBomTree.getObjectNumber());
                        cfpartMap.put(partBomTree.getObjectNumber(), partBomTree);
                    }

                }
            }
        }

        Map<String, Object> erpListMap = new HashMap<>();
        if (objectNumbers.size() > 0) {
            List<JSONObject> erpList = getErpImmediateInventory(objectNumbers, executionType);
            if (erpList != null && erpList.size() > 0) {
                for (int z = 0; z < erpList.size(); z++) {
                    erpListMap.put(erpList.get(z).getString("FNumber"), erpList.get(z).getDoubleValue("FBaseQty"));
                }
            }
        }
        //重新计算数量
        for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
            PartBomTree partBomTree = result.getPartBomTreeList().get(y);
            if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                if (partBomTree.getIsLeafNode() == true) {
                    if (erpListMap.containsKey(partBomTree.getObjectNumber())) {
                        double cy = (double) erpListMap.get(partBomTree.getObjectNumber()) - partBomTree.getAmount();
                        if (cy < 0) {
                            partBomTree.setAmount(cy);
                        }
                    } else {
                        result.getPartBomTreeList().remove(y);
                        y--;
                    }
                }
            }
        }

        //判断是采购但还是出库单
        for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
            PartBomTree partBomTree = result.getPartBomTreeList().get(y);
            if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                if (partBomTree.getIsLeafNode() == true) {
                    if (partBomTree.getAmount() < 0) {
                        result.getPartBomTreeList().remove(y);
                        y--;
                    }
                }
            }
        }

        if (result.getPartBomTreeList().size() > 1) {
            for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                    if (partBomTree.getIsLeafNode() == true) {

                        BigInteger partOid = new BigInteger(partBomTree.getPartoid());
                        String partType = partBomTree.getPartotype();
                        PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(partOid, partType);

                        //父级物料部门属性赋值到子级
                        if (parent != null) {
                            Map<String, List<String>> partMap = partDetailsVO.getIbaAttributeMap();
                            if (partMap == null) {
                                partMap = new HashMap<>();
                            }
                            Map<String, List<String>> parentMap = parent.getIbaAttributeMap();
                            if (parentMap.containsKey("申请部门")) {
                                partMap.put("申请部门", parentMap.get("申请部门"));
                            }
                            if (parentMap.containsKey("项目号")) {
                                partMap.put("项目号", parentMap.get("项目号"));
                            }
                        }

                        JSONObject partJson = JSONObject.parseObject(JSONObject.toJSONString(partDetailsVO));

                        List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(
                                partDetailsVO.getClassId());
                        if (baseCodeList != null && baseCodeList.size() > 0) {
                            partJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
                        }

                        Map<String, Object> partKeyValue = new HashMap<>();
                        for (Map<String, Object> option : options) {
                            if ("类型属性".equals(option.get("plmtype"))) {
                                k3CloudHttpService.setInTree(
                                        (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")),
                                        partJson, partKeyValue);
                                break;
                            }
                        }


                        BigInteger oid = partBomTree.getOid();
                        String oType = partBomTree.getOtype();
                        PartUsageLink partUsageLink = plmPartOptionUtils.getPartUsageLink(oid, oType);
                        partUsageLink.setAmount(partBomTree.getAmount());

                        JSONObject voJson = JSONObject.parseObject(JSONObject.toJSONString(partUsageLink));
                        Map<String, Object> voJsonMap = voJson.getInnerMap();

                        String plm_source_type_id = null;
                        Map<String, Object> listKeyValue = new HashMap<>();
                        for (Map<String, Object> option : options) {
                            if ("BOM属性".equals(option.get("plmtype"))) {
                                plm_source_type_id = (String) option.get("plm_source_type_id");
                                k3CloudHttpService.setInTree((List<Map<String, Object>>) inMap.get(plm_source_type_id),
                                                             voJsonMap, listKeyValue);
                                break;
                            }
                        }
                        listKeyValue.putAll(partKeyValue);

                        if (bomKeyValue.containsKey(plm_source_type_id)) {
                            List<Map<String, Object>> bomList = (List<Map<String, Object>>) bomKeyValue.get(
                                    plm_source_type_id);
                            bomList.add(listKeyValue);
                        } else {
                            List<Map<String, Object>> bomList = new ArrayList<>();
                            bomList.add(listKeyValue);
                            bomKeyValue.put(plm_source_type_id, bomList);
                        }
                    }
                } else {

                    BigInteger oid = new BigInteger(partBomTree.getPartoid());
                    String oType = partBomTree.getPartotype() + "|" + partBomTree.getOtype();
                    PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(oid, oType);

                    JSONObject partJson = JSONObject.parseObject(JSONObject.toJSONString(partDetailsVO));
                    List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(partDetailsVO.getClassId());
                    if (baseCodeList != null && baseCodeList.size() > 0) {
                        partJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
                    }

                    Map<String, Object> partKeyValue = new HashMap<>();
                    for (Map<String, Object> option : options) {
                        if ("类型属性".equals(option.get("plmtype"))) {
                            k3CloudHttpService.setInTree(
                                    (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")), partJson,
                                    partKeyValue);
                            break;
                        }
                    }
                    bomKeyValue.putAll(partKeyValue);
                }
            }

            Map<String, Object> out = k3CloudHttpService.plmToK3CloudOut(code, k3cloud, new HashMap<>(), bomKeyValue);

            //用ERP的用户信息值替换出参中的值
            if (out.containsKey("Model")) {
                Map<String, Object> Model = (Map<String, Object>) out.get("Model");
                Map<String, Object> F_WKYT_SQR = (Map<String, Object>) Model.get("F_WKYT_SQR");

                F_WKYT_SQR.put("FSTAFFNUMBER", userJson.getString("StaffNumber"));

                Map<String, Object> FDeptId = (Map<String, Object>) Model.get("FDeptId");
                FDeptId.put("FNumber", userJson.getString("PostDept"));
            }

            List<String> erpNumbers = new ArrayList<>();

            JSONObject resultJson = SendErpDataUtils.sendErpDataTaskWorkder(executionType, out);
            JSONObject Result = resultJson.getJSONObject("Result");
            if (Result != null) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());

                }
                else{
                    JSONArray successEntitys = ResponseStatus.getJSONArray("SuccessEntitys");
                    if (successEntitys.size() > 0) {
                        String erpNumber = successEntitys.getJSONObject(0).getString("Number");
                        erpNumbers.add(erpNumber);
                    }
                }
            }

            executionType.put("code","TJ000006X");
            resultJson=SubmissionAndReviewHanding.submitt(executionType,erpNumbers);

            return resultJson;

        } else {
            JSONObject resultObj = new JSONObject();
            resultObj.put("IsSuccess", true);
            resultObj.put("msg", "没有需要出库的物料");
            JSONObject responseStatus = new JSONObject();
            responseStatus.put("ResponseStatus", resultObj);
            httpResult.put("Result", responseStatus);
            k3CloudHttpService.saveLogs("","","成功", httpResult.toJSONString(), "", k3cloud, code);
            return httpResult;
        }
    }

    /**
     * 出库申请单调用
     * @param executionType
     * @return
     * @throws Exception
     */
    public JSONObject productionCall(Map<String, Object> executionType, PartBomTreeByFilterVO result,PartDetailsVO parent)
            throws Exception {

        PlmPartOptionUtils plmPartOptionUtils = SpringUtil.getBean(PlmPartOptionUtils.class);
        ErpK3cloudService erpK3cloudService = SpringUtil.getBean(ErpK3cloudService.class);
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        TyplmUserService typlmUserService = SpringUtil.getBean(TyplmUserService.class);

        String k3cloud = (String) executionType.get("k3cloud");
        String code = (String) executionType.get("code");
        executionType.put("plm_code",parent.getIdentifierDisplayName());

        UserDO userDO = typlmUserService.queryUserByKey(parent.getCreatoroid());

        //查询ERP用户
        JSONObject userJson = getErpUser(userDO, executionType);
        if (userJson == null) {
            k3CloudHttpService.saveLogs(parent.getIdentifierDisplayName(),"","失败", "查询不到ERP用户信息", "", k3cloud, code);
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException("查询不到ERP用户信息");
        }


        Map<String, Object> inMap = k3CloudHttpService.getInTreeMap(code, k3cloud);
        List<Map<String, Object>> options = k3CloudHttpService.getOptions(code, k3cloud);

        Map<String, Object> bomKeyValue = new HashMap<>();

        if (result.getPartBomTreeList().size() > 1) {
            for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                if (partBomTree.getOid() != BigInteger.valueOf(0L)) {
                    if (partBomTree.getIsLeafNode() == true) {

                        BigInteger partOid = new BigInteger(partBomTree.getPartoid());
                        String partType = partBomTree.getPartotype();
                        PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(partOid, partType);

                        //父级物料部门属性赋值到子级
                        if (parent != null) {
                            Map<String, List<String>> partMap = partDetailsVO.getIbaAttributeMap();
                            if (partMap == null) {
                                partMap = new HashMap<>();
                            }
                            Map<String, List<String>> parentMap = parent.getIbaAttributeMap();
                            if (parentMap.containsKey("申请部门")) {
                                partMap.put("申请部门", parentMap.get("申请部门"));
                            }
                            if (parentMap.containsKey("项目号")) {
                                partMap.put("项目号", parentMap.get("项目号"));
                            }
                        }

                        JSONObject partJson = JSONObject.parseObject(JSONObject.toJSONString(partDetailsVO));

                        List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(
                                partDetailsVO.getClassId());
                        if (baseCodeList != null && baseCodeList.size() > 0) {
                            partJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
                        }

                        Map<String, Object> partKeyValue = new HashMap<>();
                        for (Map<String, Object> option : options) {
                            if ("类型属性".equals(option.get("plmtype"))) {
                                k3CloudHttpService.setInTree(
                                        (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")),
                                        partJson, partKeyValue);
                                break;
                            }
                        }


                        BigInteger oid = partBomTree.getOid();
                        String oType = partBomTree.getOtype();
                        PartUsageLink partUsageLink = plmPartOptionUtils.getPartUsageLink(oid, oType);
                        partUsageLink.setAmount(partBomTree.getAmount());

                        JSONObject voJson = JSONObject.parseObject(JSONObject.toJSONString(partUsageLink));
                        Map<String, Object> voJsonMap = voJson.getInnerMap();

                        String plm_source_type_id = null;
                        Map<String, Object> listKeyValue = new HashMap<>();
                        for (Map<String, Object> option : options) {
                            if ("BOM属性".equals(option.get("plmtype"))) {
                                plm_source_type_id = (String) option.get("plm_source_type_id");
                                k3CloudHttpService.setInTree((List<Map<String, Object>>) inMap.get(plm_source_type_id),
                                                             voJsonMap, listKeyValue);
                                break;
                            }
                        }
                        listKeyValue.putAll(partKeyValue);

                        if (bomKeyValue.containsKey(plm_source_type_id)) {
                            List<Map<String, Object>> bomList = (List<Map<String, Object>>) bomKeyValue.get(
                                    plm_source_type_id);
                            bomList.add(listKeyValue);
                        } else {
                            List<Map<String, Object>> bomList = new ArrayList<>();
                            bomList.add(listKeyValue);
                            bomKeyValue.put(plm_source_type_id, bomList);
                        }
                    }
                } else {

                    BigInteger oid = new BigInteger(partBomTree.getPartoid());
                    String oType = partBomTree.getPartotype() + "|" + partBomTree.getOtype();
                    PartDetailsVO partDetailsVO = plmPartOptionUtils.getPartDetailsVO(oid, oType);

                    JSONObject partJson = JSONObject.parseObject(JSONObject.toJSONString(partDetailsVO));
                    List<Map<String, Object>> baseCodeList = erpK3cloudService.getBaseCode(partDetailsVO.getClassId());
                    if (baseCodeList != null && baseCodeList.size() > 0) {
                        partJson.put("baseClassificationCode", baseCodeList.get(0).get("objectnumber"));
                    }

                    Map<String, Object> partKeyValue = new HashMap<>();
                    for (Map<String, Object> option : options) {
                        if ("类型属性".equals(option.get("plmtype"))) {
                            k3CloudHttpService.setInTree(
                                    (List<Map<String, Object>>) inMap.get(option.get("plm_source_type_id")), partJson,
                                    partKeyValue);
                            break;
                        }
                    }
                    bomKeyValue.putAll(partKeyValue);
                }
            }

            Map<String, Object> out = k3CloudHttpService.plmToK3CloudOut(code, k3cloud, new HashMap<>(), bomKeyValue);

            //用ERP的用户信息值替换出参中的值
            if (out.containsKey("Model")) {
                Map<String, Object> Model = (Map<String, Object>) out.get("Model");
                Map<String, Object> F_WKYT_SQR = (Map<String, Object>) Model.get("F_WKYT_SQR");

                F_WKYT_SQR.put("FSTAFFNUMBER", userJson.getString("StaffNumber"));

                Map<String, Object> FDeptId = (Map<String, Object>) Model.get("FDeptId");
                FDeptId.put("FNumber", userJson.getString("PostDept"));
            }


            List<String> erpNumbers = new ArrayList<>();
            JSONObject resultJson = SendErpDataUtils.sendErpDataTaskWorkder(executionType, out);
            JSONObject Result = resultJson.getJSONObject("Result");
            if (Result != null) {
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == false) {
                    throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(
                            ResponseStatus.get("Errors").toString());

                }
                else{
                    JSONArray successEntitys = ResponseStatus.getJSONArray("SuccessEntitys");
                    if (successEntitys.size() > 0) {
                        String erpNumber = successEntitys.getJSONObject(0).getString("Number");
                        erpNumbers.add(erpNumber);
                    }
                }
            }

            executionType.put("code","TJ000006X");
            resultJson=SubmissionAndReviewHanding.submitt(executionType,erpNumbers);

            return resultJson;

        } else {
            JSONObject httpResult=new JSONObject();
            JSONObject resultObj = new JSONObject();
            resultObj.put("IsSuccess", true);
            resultObj.put("msg", "没有需要出库的物料");
            JSONObject responseStatus = new JSONObject();
            responseStatus.put("ResponseStatus", resultObj);
            httpResult.put("Result", responseStatus);
            k3CloudHttpService.saveLogs(parent.getIdentifierDisplayName(),"","成功", httpResult.toJSONString(), "", k3cloud, code);
            return httpResult;
        }
    }
    /**
     * 读取ERP库存数据
     *
     * @param objectNumbers
     * @return
     * @throws Exception
     */
    public List<JSONObject> getErpImmediateInventory(List<String> objectNumbers, Map<String, Object> executionType)
            throws Exception {
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        SendErpDataUtils.init();

        String port = (String) executionType.get("port");
        String home = (String) executionType.get("home");

        JSONObject outMap = new JSONObject();
        outMap.put("FormId", "STK_Inventory");
        outMap.put("TopRowCount", 0);
        outMap.put("StartRow", 0);
        outMap.put("Limit", 99999999);


        JSONArray FilterStringJson = new JSONArray();
        JSONObject FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FMaterialId.FNumber");
        FilterStringObject.put("Compare", 338);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        String number = "";
        for (int i = 0; i < objectNumbers.size(); i++) {
            if (i > 0) {
                number += ",";
            }
            number += objectNumbers.get(i);
        }
        FilterStringObject.put("Value", number);
        FilterStringJson.add(FilterStringObject);


        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "车间");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "报废");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "不良");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "封存");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        FilterStringObject = new JSONObject();
        FilterStringObject.put("FieldName", "FStockName");
        FilterStringObject.put("Compare", 34);
        FilterStringObject.put("Logic", 0);
        FilterStringObject.put("Value", "中转");
        FilterStringObject.put("Left", "");
        FilterStringObject.put("Right", "");
        FilterStringJson.add(FilterStringObject);

        //库存物料编码，库存量(基本单位),库存名称,规格型号，基本单位，库存状态
        String FieldKeys = "FMaterialId.FNumber,FMaterialName,FBaseQty,FModel,FStockUnitId.FName,FStockStatusId.FName";
        outMap.put("FieldKeys", FieldKeys);
        outMap.put("FilterString", FilterStringJson);

        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI",true);
        if (k3CloudHttpService.getCookieStr() == null) {
            Map<String, Object> login = new HashMap<>();
            login.put("acctID", SendErpDataUtils.acctID);
            login.put("lcid", 2052);
            login.put("username", SendErpDataUtils.username);
            login.put("password", SendErpDataUtils.password);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                        login);
        }
        if (httpResult.getBoolean("IsSuccessByAPI")) {
            Map<String, Object> outParameter = new HashMap<>();
            outParameter.put("formid", "STK_Inventory");
            outParameter.put("data", outMap);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                        outParameter);
            if (httpResult.containsKey("Result")) {
                JSONObject resultObj = httpResult.getJSONObject("Result");
                JSONObject responseStatus = resultObj.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if (responseStatus.getLongValue("MsgCode") == 1) {
                        k3CloudHttpService.setCookieStr(null);
                        k3CloudHttpService.setKdserviceSessionid(null);

                        Map<String, Object> login = new HashMap<>();
                        login.put("acctID", SendErpDataUtils.acctID);
                        login.put("lcid", 2052);
                        login.put("username", SendErpDataUtils.username);
                        login.put("password", SendErpDataUtils.password);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                    home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                                    login);
                        if (httpResult.containsKey("IsSuccess")) {
                            if (httpResult.getBoolean("IsSuccess")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                                            outParameter);
                            }

                        } else if (httpResult.containsKey("IsSuccessByAPI")) {
                            if (httpResult.getBoolean("IsSuccessByAPI")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc",
                                                                                            outParameter);
                            }
                        }
                    }
                }
            }

            List<JSONObject> list = new ArrayList<>();
            if (httpResult != null) {
                if (httpResult.containsKey("Result") == false && httpResult.containsKey("messages")) {
                    JSONArray resultList = httpResult.getJSONArray("messages");
                    for (int i = 0; i < resultList.size(); i++) {
                        JSONArray value = resultList.getJSONArray(i);
                        JSONObject entity = new JSONObject();
                        entity.put("FNumber", value.get(0));
                        entity.put("FMaterialName", value.get(1));
                        entity.put("FBaseQty", value.get(2));
                        entity.put("FModel", value.get(3));
                        entity.put("FStockUnitIdFName", value.get(4));
                        entity.put("FStockStatusIdFName", value.get(5));
                        list.add(entity);
                    }
                    return list;
                }
            }
        }

        return null;
    }

    @Override
    public JSONObject productionCall(Map<String, Object> executionType, FlowObject flowObject) throws Exception {
        return null;
    }

    /**
     * 查询ERP用户信息
     *
     * @param userDO
     * @param executionType
     * @return
     * @throws Exception
     */
    public JSONObject getErpUser(UserDO userDO, Map<String, Object> executionType)
            throws Exception {
        K3CloudHttpService k3CloudHttpService = SpringUtil.getBean(K3CloudHttpService.class);
        SendErpDataUtils.init();

        String port = (String) executionType.get("port");
        String home = (String) executionType.get("home");

        JSONObject outMap = new JSONObject();
        outMap.put("CreateOrgId", 0);
        outMap.put("Id", "");
        outMap.put("IsSortBySeq", false);
        outMap.put("Number", userDO.getName());

        //库存物料编码，库存量(基本单位),库存名称,规格型号，基本单位，库存状态

        JSONObject httpResult = new JSONObject();
        httpResult.put("IsSuccessByAPI", true);

        if (k3CloudHttpService.getCookieStr() == null) {
            Map<String, Object> login = new HashMap<>();
            login.put("acctID", SendErpDataUtils.acctID);
            login.put("lcid", 2052);
            login.put("username", SendErpDataUtils.username);
            login.put("password", SendErpDataUtils.password);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                        login);
        }
        if (httpResult.getBoolean("IsSuccessByAPI")) {
            Map<String, Object> outParameter = new HashMap<>();
            outParameter.put("formid", "BD_Empinfo");
            outParameter.put("data", outMap);
            httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                        home + ":" + port + "/K3Cloud//Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                        outParameter);
            if (httpResult.containsKey("Result")) {
                JSONObject resultObj = httpResult.getJSONObject("Result");
                JSONObject responseStatus = resultObj.getJSONObject("ResponseStatus");
                if (responseStatus.getBooleanValue("IsSuccess") == false) {
                    if (responseStatus.getLongValue("MsgCode") == 1) {
                        k3CloudHttpService.setCookieStr(null);
                        k3CloudHttpService.setKdserviceSessionid(null);

                        Map<String, Object> login = new HashMap<>();
                        login.put("acctID", SendErpDataUtils.acctID);
                        login.put("lcid", 2052);
                        login.put("username", SendErpDataUtils.username);
                        login.put("password", SendErpDataUtils.password);
                        httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                    home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc",
                                                                                    login);
                        if (httpResult.containsKey("IsSuccess")) {
                            if (httpResult.getBoolean("IsSuccess")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                                            outParameter);
                            }

                        } else if (httpResult.containsKey("IsSuccessByAPI")) {
                            if (httpResult.getBoolean("IsSuccessByAPI")) {
                                httpResult = k3CloudHttpService.postServiceHttpToJSONObject(HttpMethodEnum.HTTP,
                                                                                            home + ":" + port + "/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc",
                                                                                            outParameter);
                            }
                        }
                    }
                }
            }
            if (httpResult != null) {
                JSONObject Result = httpResult.getJSONObject("Result");
                JSONObject ResponseStatus = Result.getJSONObject("ResponseStatus");
                if (ResponseStatus.getBooleanValue("IsSuccess") == true) {
                    JSONObject ResultUser = Result.getJSONObject("Result");
                    JSONObject StaffId = ResultUser.getJSONObject("StaffId");
                    JSONArray PostEntity = ResultUser.getJSONArray("PostEntity");
                    if (PostEntity.size() > 0) {
                        JSONObject PostDept = PostEntity.getJSONObject(0).getJSONObject("PostDept");
                        JSONObject user = new JSONObject();
                        user.put("StaffNumber", StaffId.getString("StaffNumber"));
                        user.put("FStaffNumber", ResultUser.getString("FStaffNumber"));
                        user.put("PostDept", PostDept.getString("Number"));

                        return user;
                    }
                }
            }
        }
        return null;
    }
}
